using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using MallSystembackend.Api.Utils;
using MallSystembackend.Api.Model;
using MallSystembackend.Api.Repository;
using MallSystembackend.Api.ParamModel;
using Microsoft.Extensions.Configuration;

namespace MallSystembackend.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IRepository<Users> _usersRepository;
        private IRepository<Roles> _rolesRepository;
         private TokenParamter _tokenparamter;
         private readonly IConfiguration _configuration;
        public UsersController(IRepository<Users> usersRepository, IRepository<Roles> rolesRepository,IConfiguration configuration)
        {
            _usersRepository = usersRepository;
            _rolesRepository = rolesRepository;
            _configuration = configuration;
            _tokenparamter = _configuration.GetSection("TokenParameter").Get<TokenParamter>();
        }


        //获取用户列表
        [HttpGet]
        public ActionResult GetAllUsers([FromQuery] ParamPager model)
        {
            var CurrentPage = model.currentPage;

            var PageSize = model.pageSize;

            var roles = _rolesRepository.Table.ToList();

            var users = _usersRepository.Table.ToList();

            var user = users.Where(x => x.IsDeleted == false).Skip((CurrentPage - 1) * PageSize).Take(PageSize).ToList();

            var combinUser = (from use in user join Name in roles on use.RolesId equals Name.Id select new { use, Name.RolesName }).ToList();

            return Ok(new
            {
                Code = 1000,
                Data = combinUser,
                Count = users.Where(x => x.IsDeleted == false).Count()
            });

        }

        //根据角色id获取用户列表
        [HttpGet, Route("Roles/{id}")]
        public ActionResult GetUsersById(int id, [FromQuery] ParamPager model)
        {
            Console.WriteLine(model.currentPage);
            var CurrentPage = model.currentPage;

            var PageSize = model.pageSize;

            var roles = _rolesRepository.Table.ToList();

            var users = _usersRepository.Table;

            var user = users.Where(x => x.RolesId == id && x.IsDeleted == false).Skip((CurrentPage - 1) * PageSize).Take(PageSize).ToList();

            var combinUser = (from use in user join Name in roles on use.RolesId equals Name.Id select new { use, Name.RolesName }).ToList();

            return Ok(new
            {
                Code = 1000,
                Data = combinUser,
                Count = users.Where(x => x.RolesId == id && x.IsDeleted == false).Count()
            });
        }
        //添加用户
        [HttpPost]
        public ActionResult Post(ParamUser model)
        {
            var users = _usersRepository.Table;
            var usename = users.Where(x => x.Username == model.Username).FirstOrDefault();
            if (usename == null)
            {
                var user =
                new Users
                {
                    NickName = model.NickName,
                    Username = model.Username,
                    Password = model.Password,
                    Age = model.Age,
                    Sex = model.Sex,
                    phone = model.phone,
                    mailbox = model.mailbox,
                    RolesId = 2,
                    IsActived = true,
                    IsDeleted = false,
                    Remarks = model.Remark
                };
                _usersRepository.Insert(user);
                return Ok(new { Code = 1000, Data = user, Msg = "添加成功" });
            }
            else
            {
                return Ok(new { Code = 1002, Data = "", Msg = "账号已存在" });
            }

        }
        //登录

        [HttpPost, Route("Login")]
        public ActionResult GetToken(ParamUser model)
        {

            var users = _usersRepository.Table;

            if (model.Username.Trim() == "" || model.Password.Trim() == "")
            {
                var res = new
                {
                    Code = 1002,
                    Data = "",
                    Msg = "账号密码不能为空，请重试"
                };
                return Ok(res);
            }
            else
            {
                var user = users.Where(x => x.Username == model.Username.Trim() && x.Password == model.Password.Trim() && x.IsActived == true).FirstOrDefault();

                if (user == null)
                {
                    return Ok(
                    new
                    {
                        Code = 1002,
                        Data = "",
                        Msg = "账号密码错误或改用户被封禁，请确认后重试"
                    });

                };
                var id = user.Id;
                //如果登录成功，需要获得token
                var token = TokenHelper.GenerateToekn(_tokenparamter, user);
                var refreshToken = "123456";
                var res = new
                {
                    Code = 1000,
                    // Data=user,
                    Data = new { Token = token, RefreshToken = refreshToken, Id = id },
                    Msg = "登录成功"
                };
                return Ok(res);

            }
        }
        //根据用户id获取列表
        [HttpGet("GetOne/{id}")]
        public ActionResult GetOne(int id){
            var User=_usersRepository.GetById(id);
            if(User!=null){
                return Ok(new {
                    Code = 1000,
                    Data=User,
                    Msg = "获得成功"
                });
            }
            return Ok(new{
                Code=1002,
                Data=" ",
                Msg = "获得失败"
            });
        }

        //根据用户名获取列表
        [HttpGet, Route("select/{id}")]
        public ActionResult SelectUsername([FromQuery] ParamSelect data, int id)
        {
            var msg = data.msg;

            //获取当前页
            var currentPage = data.currentPage;

            //获取页面数据行数
            var pageSize = data.pageSize;

            var use = _usersRepository.Table;

            var u =
                use.Where(x => x.Username.Contains(msg) && x.RolesId == x.Id)
                    .Where(x => x.IsDeleted == false)
                    .Take(pageSize)
                    .ToList();

            return Ok(new
            {
                Code = 1000,
                Data = u,
                Count =
                    use.Where(x => x.Username.Contains(msg) && x.RolesId == x.Id)
                        .Where(x => x.IsDeleted == false)
                        .Count()
            });
        }

    }
}